package com.unlcn.ils.kas.service.order.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.unlcn.ils.kas.dao.mapper.order.OrderOtdMapper;
import com.unlcn.ils.kas.dao.model.order.Customer;
import com.unlcn.ils.kas.dao.model.order.OrderOtd;
import com.unlcn.ils.kas.dao.model.order.OrderOtdDetail;
import com.unlcn.ils.kas.dao.model.order.bo.*;
import com.unlcn.ils.kas.service.bo.ErpOrderSelectDetail;
import com.unlcn.ils.kas.service.bo.ErpOrderSelectHead;
import com.unlcn.ils.kas.service.interfaceLog.InterfaceLogService;
import com.unlcn.ils.kas.service.map.BaiDuMap.util.BaiDuMapGeocodeUtil;
import com.unlcn.ils.kas.service.map.BaiDuMap.util.BaiDuMapRouteUtil;
import com.unlcn.ils.kas.service.order.CustomerService;
import com.unlcn.ils.kas.service.order.OrderOtdDetailService;
import com.unlcn.ils.kas.service.order.OrderOtdService;
import com.unlcn.ils.kas.service.util.BaseException;
import com.unlcn.ils.kas.service.util.DateUtils;
import com.unlcn.ils.kas.service.util.enums.ErrorCodeEnum;
import com.unlcn.ils.kas.service.util.enums.order.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 订单在途跟踪 服务实现类
 *
 * @author 罗必量
 * @since 2018-03-06
 */
@Service
public class OrderOtdServiceImpl extends ServiceImpl<OrderOtdMapper, OrderOtd> implements OrderOtdService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderOtdServiceImpl.class);

    @Autowired
    private OrderOtdMapper orderOtdMapper;

    @Autowired
    private OrderOtdDetailService orderOtdDetailService;

    @Autowired
    private InterfaceLogService interfaceLogService;

    @Autowired
    private CustomerService customerService;

    private final int LIMIT_DAYS = 31;

    @Override
    public Page<OrderLineBo> queryPage(Page<OrderOtd> page) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        EntityWrapper<OrderOtd> ew = new EntityWrapper<>();
        // 查询条件
        if (!StringUtils.isEmpty(page.getCondition())) {
            // 单个系统订单号用like 否则in
            if (!StringUtils.isEmpty(page.getCondition().get("sysOrderNo"))) {
                String[] sysnoLst = page.getCondition().get("sysOrderNo").toString().split("\\s+");
                if (sysnoLst.length == 1) {
                    ew.like("sys_order_no", sysnoLst[0]);
                } else {
                    ew.in("sys_order_no", sysnoLst);
                }
            }
            // 客户订单号
            if (!StringUtils.isEmpty(page.getCondition().get("customerOrderNo"))) {
                ew.like("customer_order_no", page.getCondition().get("customerOrderNo").toString());
            }
            // 客户编号
            if (!StringUtils.isEmpty(page.getCondition().get("customerNo"))) {
                ew.eq("customer_no", page.getCondition().get("customerNo").toString());
            }
            try {
                // 订单起始日期
                if (!StringUtils.isEmpty(page.getCondition().get("startOrderTime"))) {
                    ew.ge("order_create_time", format.parse(page.getCondition().get("startOrderTime").toString()));
                }
                // 订单截至日期
                if (!StringUtils.isEmpty(page.getCondition().get("endOrderTime"))) {
                    ew.lt("order_create_time", format.parse(page.getCondition().get("endOrderTime").toString()));
                }
                // 起始打单时间
                if (page.getCondition() != null
                        && !StringUtils.isEmpty(page.getCondition().get("startPrintOrderTime"))) {
                    ew.ge("printOrder_time", format.parse(page.getCondition().get("startPrintOrderTime").toString()));
                }
                // 截至打单时间
                if (page.getCondition() != null && !StringUtils.isEmpty(page.getCondition().get("endPrintOrderTime"))) {
                    ew.lt("printOrder_time", format.parse(page.getCondition().get("endPrintOrderTime").toString()));
                }
                // 起始回单时间
                if (page.getCondition() != null
                        && !StringUtils.isEmpty(page.getCondition().get("startReturnOrderTime"))) {
                    ew.ge("returnOrder_time", format.parse(page.getCondition().get("startReturnOrderTime").toString()));
                }
                // 截至回单时间
                if (page.getCondition() != null
                        && !StringUtils.isEmpty(page.getCondition().get("endReturnOrderTime"))) {
                    ew.lt("returnOrder_time", format.parse(page.getCondition().get("endReturnOrderTime").toString()));
                }
            } catch (Exception e) {
                LOGGER.error("OrderOtdServiceImpl.queryPage ERROR Message : {} ", e);
            }

            // 收车省
            if (!StringUtils.isEmpty(page.getCondition().get("dProvince"))) {
                ew.eq("d_province", page.getCondition().get("dProvince").toString());
            }
            // 收车市
            if (!StringUtils.isEmpty(page.getCondition().get("dCity"))) {
                ew.like("d_city", page.getCondition().get("dCity").toString());
            }
            // 订单状态
            if (!StringUtils.isEmpty(page.getCondition().get("orderStatus"))) {
                ew.eq("order_status", page.getCondition().get("orderStatus").toString());
            }
            // 运输方式
            if (!StringUtils.isEmpty(page.getCondition().get("transportType"))) {
                ew.eq("transport_type", page.getCondition().get("transportType").toString());
            }
            // 车牌号
            if (!StringUtils.isEmpty(page.getCondition().get("licensePlate"))) {
                ew.like("license_plate", page.getCondition().get("licensePlate").toString());
            }
            // 车架号
            // 单个车架号用like 否则in
            if (!StringUtils.isEmpty(page.getCondition().get("vin"))) {
                String[] vins = page.getCondition().get("vin").toString().split("\\s+");
                if (vins.length == 1) {
                    ew.like("vin", vins[0]);
                } else {
                    ew.in("vin", vins);
                }
            }
            // 无车承运人
            if (!StringUtils.isEmpty(page.getCondition().get("supplier"))) {
                ew.eq("supplier", page.getCondition().get("supplier").toString());
            }
            // 经销商
            if (!StringUtils.isEmpty(page.getCondition().get("dealerName"))) {
                ew.eq("dealer_name", page.getCondition().get("dealerName").toString());
            }
        }
        page.setRecords(orderOtdMapper.selectPage(page, ew));

        Page<OrderLineBo> returnPage = new Page<>();
        BeanUtils.copyProperties(page, returnPage);

        List<OrderOtd> orderOtdList = page.getRecords();
        List<OrderLineBo> orderLineBoList = new ArrayList<>();
        for (OrderOtd orderOtd : orderOtdList) {
            OrderLineBo orderLineBo = new OrderLineBo();
            BeanUtils.copyProperties(orderOtd, orderLineBo);

            // 查询记录数
            Wrapper<OrderOtdDetail> detailEntity = new EntityWrapper<>();
            detailEntity.eq("sys_order_no", orderOtd.getSysOrderNo());
            detailEntity.eq("isdelete", OrderDetailDeleteFlagEnum.NORMAL.getCode());
            Integer recordCount = orderOtdDetailService.selectCount(detailEntity);
            orderLineBo.setRecordCount(recordCount);

            orderLineBoList.add(orderLineBo);
        }
        returnPage.setRecords(orderLineBoList);

        return returnPage;
    }

    @Override
    public OrderModifyInfoBo findModifyInfo(Long id) {
        if (id == null)
            throw new BaseException(OrderExceptionEnum.ID_NOT_NULL.getCode(), OrderExceptionEnum.ID_NOT_NULL.getText());

        OrderModifyInfoBo orderModifyInfoBo = new OrderModifyInfoBo();

        // 查找订单信息
        OrderOtd orderOtd = orderOtdMapper.selectById(id);
        BeanUtils.copyProperties(orderOtd, orderModifyInfoBo);

        // 查找订单在途信息
        Wrapper<OrderOtdDetail> detailEntity = new EntityWrapper<>();
        detailEntity.eq("sys_order_no", orderOtd.getSysOrderNo());
        detailEntity.eq("isdelete", OrderDetailDeleteFlagEnum.NORMAL.getCode());
        detailEntity.orderBy(" track_time desc ");
        List<OrderOtdDetail> orderOtdDetails = orderOtdDetailService.selectList(detailEntity);
        orderModifyInfoBo.setOrderOtdDetails(orderOtdDetails);

        return orderModifyInfoBo;
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public void modifyInfo(OrderModifyInfoBo orderModifyInfoBo) {
        if (orderModifyInfoBo == null)
            throw new BaseException(OrderExceptionEnum.MODIFY_INFO_NOT_NULL.getCode(),
                    OrderExceptionEnum.MODIFY_INFO_NOT_NULL.getText());

        // 查找更新订单信息
        OrderOtd selectOrder = orderOtdMapper.selectById(orderModifyInfoBo.getId());
        if (selectOrder == null)
            throw new BaseException(OrderExceptionEnum.MODIFY_DATA_NOT_FOUND.getCode(),
                    OrderExceptionEnum.MODIFY_DATA_NOT_FOUND.getText());

        // 更新订单信息
        OrderOtd orderOtd = new OrderOtd();
        BeanUtils.copyProperties(orderModifyInfoBo, orderOtd);
        orderOtd.setManualShiptoTime(orderModifyInfoBo.getShiptoTime());
        if (orderModifyInfoBo.getShiptoTime() != null) {
            orderOtd.setPlanShiptoTime(orderModifyInfoBo.getShiptoTime());
            orderOtd.setNewestTime(orderModifyInfoBo.getShiptoTime());

            String newestPosition = (StringUtils.isEmpty(selectOrder.getdProvince()) ? ""
                    : selectOrder.getdProvince() + "-")
                    + (StringUtils.isEmpty(selectOrder.getdCity()) ? "" : selectOrder.getdCity() + "-")
                    + (StringUtils.isEmpty(selectOrder.getdAddress()) ? "" : selectOrder.getdAddress());
            orderOtd.setNewestPosition(newestPosition);
        }
        orderOtd.setManualDriverPhone(orderModifyInfoBo.getDriverPhone());

        // 判断运单状态
        if (orderOtd.getLeaveTime() == null) {
            orderOtd.setOrderStatus("未离昌");
        }
        if (orderOtd.getLeaveTime() != null) {
            orderOtd.setOrderStatus("在途");
        }
        if (orderOtd.getShiptoTime() != null) {
            orderOtd.setOrderStatus("交付");
        }

        if (orderOtd.getTransportType().contains("单层")) {
            orderOtd.setTransportTypeCode(4);
        }
        if (orderOtd.getTransportType().contains("双层")) {
            orderOtd.setTransportTypeCode(5);
        }
        if (orderOtd.getTransportType().contains("六位板")) {
            orderOtd.setTransportTypeCode(7);
        }
        if (orderOtd.getTransportType().contains("三位板")) {
            orderOtd.setTransportTypeCode(8);
        }
        if (orderOtd.getTransportType().contains("-")) {
            orderOtd.setTransportTypeCode(0);
        }
        if (orderOtd.getTransportType().contains("人送")) {
            orderOtd.setTransportTypeCode(1);
        }
        if (orderOtd.getTransportType().contains("零公里")) {
            orderOtd.setTransportTypeCode(2);
        }
        if (orderOtd.getTransportType().contains("水运")) {
            orderOtd.setTransportTypeCode(3);
        }
        if (orderOtd.getTransportType().contains("四位板")) {
            orderOtd.setTransportTypeCode(6);
        }
        if (orderOtd.getTransportType().contains("中置轴")) {
            orderOtd.setTransportTypeCode(15);
        }

        // 数据源
        orderOtd.setWay(OrderWayEnum.WAY_MABUAL.getCode());

        orderOtdMapper.updateOrder(orderOtd);

        // 查找订单在途信息是否存在增删操作
        Wrapper<OrderOtdDetail> detailEntity = new EntityWrapper<>();
        detailEntity.eq("sys_order_no", orderModifyInfoBo.getSysOrderNo());
        detailEntity.eq("isdelete", OrderDetailDeleteFlagEnum.NORMAL.getCode());
        List<OrderOtdDetail> otdDetailList = orderOtdDetailService.selectList(detailEntity);
        List<OrderOtdDetail> orderOtdDetails = orderModifyInfoBo.getOrderOtdDetails();
        // 查出的在途信息是否等于空
        if (CollectionUtils.isEmpty(otdDetailList)) {
            // 查出的在途信息等于空，也没有没有新增，则返回不更新在途信息
            if (CollectionUtils.isEmpty(orderOtdDetails))
                return;

            // 批量新增订单在途信息
            for (OrderOtdDetail orderOtdDetail : orderOtdDetails) {
                saveDetail(orderOtd, orderOtdDetail);
            }
        } else {
            List<Long> ids = new ArrayList<Long>();
            // 删除全部在途信息
            if (CollectionUtils.isEmpty(orderOtdDetails)) {
                for (OrderOtdDetail orderOtdDetail : otdDetailList) {
                    ids.add(orderOtdDetail.getId());
                }
                orderOtdDetailService.deleteBatchIds(ids);
            }

            // 检查有没有新增的订单在途信息
            if (!CollectionUtils.isEmpty(orderOtdDetails)) {
                for (OrderOtdDetail orderOtdDetail : orderOtdDetails) {
                    // 如果等于空，则是新增信息
                    if (orderOtdDetail.getId() == null) {
                        // 判断明细是否已经存在，存在则不再保存
                        Wrapper<OrderOtdDetail> detailWrapper = new EntityWrapper<>();
                        detailWrapper.eq("track_time", orderOtdDetail.getTrackTime());
                        List<OrderOtdDetail> details = orderOtdDetailService.selectList(detailWrapper);
                        if (!CollectionUtils.isEmpty(details))
                            continue;

                        saveDetail(orderOtd, orderOtdDetail);
                    }
                }
            }

            // 检查有没有删除的订单在途信息
            for (OrderOtdDetail orderOtdDetail : otdDetailList) {
                boolean haveDetele = true;
                for (OrderOtdDetail orderOtdDetail2 : orderOtdDetails) {
                    if (orderOtdDetail.getId().equals(orderOtdDetail2.getId())) {
                        haveDetele = false;
                        break;
                    }
                }
                if (haveDetele)
                    ids.add(orderOtdDetail.getId());
            }
            // 更新订单在途信息
            if (!CollectionUtils.isEmpty(ids))
                orderOtdDetailService.deleteBatchIds(ids);
        }

        OrderOtdDetail orderOtdDetail = orderOtdDetailService.selectNewestInfo(orderOtd.getSysOrderNo());
        if (orderOtdDetail != null && orderModifyInfoBo.getShiptoTime() == null) {
            // 更新订单最新在途时间和位置
            OrderOtd updateOrder = new OrderOtd();
            updateOrder.setId(orderOtd.getId());
            updateOrder.setNewestTime(orderOtdDetail.getTrackTime());
            String newestPosition = orderOtdDetail.getProvince() + orderOtdDetail.getCity() + orderOtdDetail.getArea()
                    + orderOtdDetail.getAddress();
            newestPosition = newestPosition.replaceAll("null", "");
            updateOrder.setNewestPosition(newestPosition);
            orderOtdMapper.updateById(updateOrder);
        }

        // 如果运抵时间不为空，则创建一条在途明细
        if (orderModifyInfoBo.getShiptoTime() != null) {
            EntityWrapper<OrderOtdDetail> ew = new EntityWrapper<>();
            ew.eq("sys_order_no", orderOtd.getSysOrderNo());
            ew.eq("track_time", orderOtd.getNewestTime());
            int count = orderOtdDetailService.selectCount(ew);

            if (count <= 0) {
                OrderOtdDetail newOrdDetail = new OrderOtdDetail();
                newOrdDetail.setTrackTime(orderOtd.getNewestTime());
                newOrdDetail.setAddress(orderOtd.getNewestPosition());
                newOrdDetail.setProvince(orderOtd.getdProvince());
                newOrdDetail.setCity(orderOtd.getdCity());
                newOrdDetail.setDistance(0f);

                // 是否手动添加（是）
                newOrdDetail.setIsmanual(OrderDetailIsmanualEnum.YES.getCode());
                saveDetail(orderOtd, newOrdDetail);

            }
        }

    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public void saveDetail(OrderOtd orderOtd, OrderOtdDetail orderOtdDetail) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 保存手动维护的明细
        orderOtdDetail.setHeadId(orderOtd.getId());
        orderOtdDetail.setSysOrderNo(orderOtd.getSysOrderNo());
        orderOtdDetail.setIsmanual(OrderDetailIsmanualEnum.YES.getCode());
        orderOtdDetailService.insert(orderOtdDetail);

        // 删除比手动维护的时间要晚，并且距离要远的数据
        OrderOtdDetail updateDetail = new OrderOtdDetail();
        updateDetail.setIsdelete(OrderDetailDeleteFlagEnum.DELETE.getCode());
        Wrapper<OrderOtdDetail> wrapper = new EntityWrapper<>();
        wrapper.eq("sys_order_no", orderOtdDetail.getSysOrderNo());
        wrapper.eq("ismanual", OrderDetailIsmanualEnum.NO.getCode());
        wrapper.gt("track_time", simpleDateFormat.format(orderOtdDetail.getTrackTime()));
        wrapper.gt("distance", orderOtdDetail.getDistance());
        wrapper.eq("isdelete", OrderDetailDeleteFlagEnum.NORMAL.getCode());
        orderOtdDetailService.update(updateDetail, wrapper);
    }

    @Override
    public Map<String, Object> getLatLon(String address, String endAddress) {

        Map<String, Object> map = new HashMap<>();

        map.put("latlon", BaiDuMapGeocodeUtil.addressToGPS(address));

        BaiDuMapRouteUtil baiDuMapRouteUtil = new BaiDuMapRouteUtil();
        Number distance = baiDuMapRouteUtil.getDistance(address, endAddress);
        distance = distance.intValue() / 1000;
        map.put("distance", distance);

        return map;
    }

    @Override
    public List<Customer> getCustomer() {
        Wrapper<Customer> entityWrapper = new EntityWrapper<>();
        return customerService.selectList(entityWrapper);
    }

    @Override
    public List<ErpOrderSelectHeadBo> orderSelect(Long startTime, Long endTime, String customerNo) {
        List<ErpOrderSelectHeadBo> orderSelectHeads = new ArrayList<>();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        orderSelectHeads = orderOtdMapper.erpSelectDetail(format.format(new Date(startTime)),
                format.format(new Date(endTime)), customerNo);

        return orderSelectHeads;
    }

    @Override
    public List<OrderOtd> getKasOrderOtdByCustomerOtdList(String customerCode) throws Exception {
        EntityWrapper<OrderOtd> ew = new EntityWrapper<>();
        ew.where("sys_order_no={0}", customerCode).or("customer_order_no={0}", customerCode).orderBy("id", false);
        List<OrderOtd> otdLists = orderOtdMapper.selectList(ew);
        return otdLists;
    }

    @Override
    public List<OrderForCustcomerBo> selectListByConditionsForCust(HttpServletRequest request,
            Map<String, Object> params) {
        List<OrderForCustcomerBo> kasCustomerOtdList = null;

        LOGGER.info("OTDServiceImpl.selectListByConditionsForCust params:{}.", params);

        // 日志
        InterfaceLogBo interfaceLogBo = new InterfaceLogBo();
        interfaceLogBo.setCreateTime(new Date());
        interfaceLogBo.setInterfaceName("第三方物流的整车运输信息查询接口");
        interfaceLogBo.setInterfaceUrl("/tranportInfo");
        interfaceLogBo.setRequestUser(request.getLocalAddr());
        interfaceLogService.insert(interfaceLogBo);

        try {
            validParma(params);
        } catch (IllegalArgumentException e) {
            LOGGER.error("select list by conditions for cust param valid:{}.", e.getMessage());
            // 更新日志
            interfaceLogBo.setResult("error");
            interfaceLogBo.setResultDesc(e.getMessage());
            interfaceLogService.update(interfaceLogBo);
            throw new BaseException(e.getMessage());
        }

        try {
            Map<String, Object> paramsMap = Maps.newHashMap();

            String orderByClause = " gmt_create desc";
            paramsMap.put("orderByClause", orderByClause);

            if (params.containsKey("customer_order_code")
                    && org.apache.commons.lang3.StringUtils.isNotEmpty(params.get("customer_order_code").toString())) {
                String[] customerOrderCodeArray = params.get("customer_order_code").toString().replace(" ", "")
                        .split(",|;");
                paramsMap.put("customerOrderCodeArray", customerOrderCodeArray);
            }

            if (params.containsKey("order_code")
                    && org.apache.commons.lang3.StringUtils.isNotEmpty(params.get("order_code").toString())) {
                String[] orderCodeArray = params.get("order_code").toString().replace(" ", "").split(",|;");
                paramsMap.put("orderCode", orderCodeArray);
            }

            if (params.containsKey("arrive_timeF")
                    && org.apache.commons.lang3.StringUtils.isNotEmpty(params.get("arrive_timeF").toString())) {
                paramsMap.put("arriveTimeBegin", params.get("arrive_timeF"));
            }

            if (params.containsKey("arrive_timeT")
                    && org.apache.commons.lang3.StringUtils.isNotEmpty(params.get("arrive_timeT").toString())) {
                Date arriveEndTime = DateUtils.addDays(StrToDate(params.get("arrive_timeT").toString()), 1);
                paramsMap.put("arriveTimeEnd", DateUtils.getStringFromDate(arriveEndTime, "yyyy-MM-dd"));
            }

            if (params.containsKey("client_code")
                    && org.apache.commons.lang3.StringUtils.isNotEmpty(params.get("client_code").toString())) {
                CustomCodeEnum accountStatusEnum = CustomCodeEnum
                        .getByValue(params.get("client_code").toString().trim());
                paramsMap.put("customerName", accountStatusEnum.getMsg());

                if ("JMC"== params.get("client_code").toString().trim()){
                    paramsMap.put("inZLZONE",true);
                }
            }

           

            if (params.containsKey("shipment_timeF")
                    && org.apache.commons.lang3.StringUtils.isNotEmpty(params.get("shipment_timeF").toString())) {
                paramsMap.put("shipmentTimeBegin", params.get("shipment_timeF"));
            }

            if (params.containsKey("shipment_timeT")
                    && org.apache.commons.lang3.StringUtils.isNotEmpty(params.get("shipment_timeT").toString())) {
                Date shipmentEndTime = DateUtils.addDays(StrToDate(params.get("shipment_timeT").toString()), 1);
                paramsMap.put("shipmentTimeEnd", DateUtils.getStringFromDate(shipmentEndTime, "yyyy-MM-dd"));
            }

            if (params.containsKey("refresh_timeF")
                    && org.apache.commons.lang3.StringUtils.isNotEmpty(params.get("refresh_timeF").toString())) {
                paramsMap.put("refreshTimeBegin", params.get("refresh_timeF"));
                LOGGER.info("refreshTimeBegin :[{}]", paramsMap.get("refreshTimeBegin").toString());
            }

            if (params.containsKey("refresh_timeT")
                    && org.apache.commons.lang3.StringUtils.isNotEmpty(params.get("refresh_timeT").toString())) {
                paramsMap.put("refreshTimeEnd", params.get("refresh_timeT"));
                LOGGER.info("refreshTimeEnd :[{}]", paramsMap.get("refreshTimeEnd").toString());
            }

            kasCustomerOtdList = orderOtdMapper.selectByConditions(paramsMap);

            // 更新日志
            interfaceLogBo.setResult("success");
            interfaceLogBo.setResultDesc("查询成功！");
            interfaceLogService.update(interfaceLogBo);

        } catch (Exception e) {
            LOGGER.error("select list by conditions for cust error :{}.", e.getMessage());
            // 更新日志
            interfaceLogBo.setResult("error");
            interfaceLogBo.setResultDesc("查询运单接口出错");
            interfaceLogService.update(interfaceLogBo);
            throw new BaseException("查询运单接口出错");
        }

        return kasCustomerOtdList;
    }

    @Override
    public List<String> getTransportType() {
        return orderOtdMapper.getTransportType();
    }

    @Override
    public List<String> getSupplier() {
        return orderOtdMapper.getSupplier();
    }

    @Override
    public List<String> getDealerName() {
        return orderOtdMapper.getDealerName();
    }

    @Override
    public List<String> getShipmentType() {
        return orderOtdMapper.getShipmentType();
    }

    @Override
    public List<String> getOrderNo(Long startTime, Long endTime, String customerNo) {
        if (startTime == null && endTime == null && StringUtils.isEmpty(customerNo))
            return new ArrayList<>();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        return orderOtdMapper.selectOrderNo(format.format(new Date(startTime)), format.format(new Date(endTime)),
                customerNo);
    }

    @Override
    public ErpOrderSelectHead getOrderDetail(String sysOrderNo) {

        ErpOrderSelectHead erpOrderSelectHead = new ErpOrderSelectHead();

        EntityWrapper<OrderOtd> ew = new EntityWrapper<>();
        ew.eq("sys_order_no", sysOrderNo);
        List<OrderOtd> orderOtdList = orderOtdMapper.selectList(ew);
        OrderOtd orderOtd = new OrderOtd();
        BeanUtils.copyProperties(orderOtd, erpOrderSelectHead);

        // 查询订单在途信息
        EntityWrapper<OrderOtdDetail> detailEntity = new EntityWrapper<>();
        detailEntity.eq("sys_order_no", orderOtd.getSysOrderNo());
        List<OrderOtdDetail> orderOtdDetailList = orderOtdDetailService.selectList(detailEntity);

        List<ErpOrderSelectDetail> orderSelectDetailList = new ArrayList<>();
        for (OrderOtdDetail orderOtdDetail : orderOtdDetailList) {
            ErpOrderSelectDetail orderSelectDetail = new ErpOrderSelectDetail();
            BeanUtils.copyProperties(orderOtdDetail, orderSelectDetail);

            if (orderOtd.getCustomerNo() != null && orderOtd.getCustomerNo().equals("1")) {
                orderSelectDetail.setPlanShiptoTime(orderOtd.getPlanShiptoTime());
            }

            orderSelectDetailList.add(orderSelectDetail);
        }

        erpOrderSelectHead.setErpOrderSelectDetailList(orderSelectDetailList);

        return erpOrderSelectHead;
    }

    @Override
    public void importUpdate(OrderOtd orderOtd) {
        orderOtdMapper.importUpdate(orderOtd);
    }

    @Override
    public List<OrderOtd> exceptionLine(Page<OrderOtd> page, Wrapper<OrderOtd> ew) {
        return orderOtdMapper.exceptionLine(page, ew);
    }

    @Override
    public List<OrderOtd> exportExceptionData(Integer customerNo, Integer classCode,
            OnWayExceptionBo onWayExceptionBo) {
        return orderOtdMapper.exportExceptionData(customerNo, classCode, onWayExceptionBo);
    }

    /**
     * 校验接口参数
     *
     * @param params
     */
    private void validParma(Map<String, Object> params) {
        if (null == params) {
            LOGGER.error("OTDServiceImpl.selectListByConditionsForCust param conditions must not be null ");
            throw new IllegalArgumentException(ErrorCodeEnum.PARAM_ISNULL.getCode());
        }

        if (!params.containsKey("client_code")
                || org.apache.commons.lang3.StringUtils.isEmpty(params.get("client_code").toString())) {
            LOGGER.error("OTDServiceImpl.selectListByConditionsForCust param:client_code must not be null ");
            throw new IllegalArgumentException(ErrorCodeEnum.CUSTOMERCODE_ISNULL.getCode());
        }

        Date shipmentTimeFromDate = null;
        Date shipmentTimeToDate = null;
        Date arriveTimeFromDate = null;
        Date arriveTimeToDate = null;
        Date refreshTimeFromDate = null;
        Date refreshTimeToDate = null;
        String orderCode = null;
        String customerOrderCode = null;

        if (params.containsKey("shipment_timeF")
                && org.apache.commons.lang3.StringUtils.isNotEmpty(params.get("shipment_timeF").toString())) {
            shipmentTimeFromDate = StrToDate(params.get("shipment_timeF").toString());
        }

        if (params.containsKey("shipment_timeT")
                && org.apache.commons.lang3.StringUtils.isNotEmpty(params.get("shipment_timeT").toString())) {
            shipmentTimeToDate = StrToDate(params.get("shipment_timeT").toString());
        }

        if (params.containsKey("refresh_timeF")
                && org.apache.commons.lang3.StringUtils.isNotEmpty(params.get("refresh_timeF").toString())) {
            refreshTimeFromDate = StrWithClockToDate(params.get("refresh_timeF").toString());
        }

        if (params.containsKey("refresh_timeT")
                && org.apache.commons.lang3.StringUtils.isNotEmpty(params.get("refresh_timeT").toString())) {
            refreshTimeToDate = StrWithClockToDate(params.get("refresh_timeT").toString());
        }

        if (params.containsKey("arrive_timeF")
                && org.apache.commons.lang3.StringUtils.isNotEmpty(params.get("arrive_timeF").toString())) {
            arriveTimeFromDate = StrToDate(params.get("arrive_timeF").toString());
        }

        if (params.containsKey("arrive_timeT")
                && org.apache.commons.lang3.StringUtils.isNotEmpty(params.get("arrive_timeT").toString())) {
            arriveTimeToDate = StrToDate(params.get("arrive_timeT").toString());
        }

        if (params.containsKey("order_code")
                && org.apache.commons.lang3.StringUtils.isNotEmpty(params.get("order_code").toString())) {
            orderCode = params.get("order_code").toString();
        }

        if (params.containsKey("customer_order_code")
                && org.apache.commons.lang3.StringUtils.isNotEmpty(params.get("customer_order_code").toString())) {
            customerOrderCode = params.get("customer_order_code").toString();
        }

        if (null == shipmentTimeFromDate && null == shipmentTimeToDate && null == arriveTimeFromDate
                && null == refreshTimeFromDate && null == refreshTimeToDate && null == arriveTimeToDate
                && org.apache.commons.lang3.StringUtils.isEmpty(customerOrderCode)
                && org.apache.commons.lang3.StringUtils.isEmpty(orderCode)) {
            LOGGER.error("OTDServiceImpl.selectListByConditionsForCust param conditions must not be null ");
            throw new IllegalArgumentException(ErrorCodeEnum.PARAM_ISNULL.getCode());
        }

        if (null != refreshTimeFromDate && null != refreshTimeToDate) {
            if (refreshTimeFromDate.after(refreshTimeToDate)) {
                LOGGER.error(
                        "OTDServiceImpl.selectListByConditionsForCust param: refresh_timeF must be less than refresh_timeT");
                throw new IllegalArgumentException(ErrorCodeEnum.REFRESHTIME_INVALID.getCode());
            }

            int daysBetween = 0;
            try {
                daysBetween = DateUtils.daysBetween(refreshTimeFromDate, refreshTimeToDate);
            } catch (ParseException e1) {
                LOGGER.error("OTDServiceImpl.selectListByConditionsForCust refresh_time between error");
                throw new IllegalArgumentException(ErrorCodeEnum.SHIPMENTTIME.getCode());
            }

            if (daysBetween > LIMIT_DAYS) {
                LOGGER.error(
                        "OTDServiceImpl.selectListByConditionsForCust refresh_timeF difference is greater than 7 days");
                throw new IllegalArgumentException(ErrorCodeEnum.DAYS_INVALID.getCode());
            }
        } else if ((null == refreshTimeFromDate && null != refreshTimeToDate)
                || (null != refreshTimeFromDate && null == refreshTimeToDate)) {
            LOGGER.error(
                    "OTDServiceImpl.selectListByConditionsForCust param: shipmenttimeF and shipmenttimeT must be coexist or not exists");
            throw new IllegalArgumentException(ErrorCodeEnum.SHIPMENTTIME.getCode());
        }

        if (null != shipmentTimeFromDate && null != shipmentTimeToDate) {
            if (shipmentTimeFromDate.after(shipmentTimeToDate)) {
                LOGGER.error(
                        "OTDServiceImpl.selectListByConditionsForCust param: shipmenttimeF must be less than shipmenttimeT");
                throw new IllegalArgumentException(ErrorCodeEnum.SHIPMENTTIME_INVALID.getCode());
            }

            int daysBetween = 0;
            try {
                daysBetween = DateUtils.daysBetween(shipmentTimeFromDate, shipmentTimeToDate);
            } catch (ParseException e1) {
                LOGGER.error("OTDServiceImpl.selectListByConditionsForCust shipmenttime between error");
                throw new IllegalArgumentException(ErrorCodeEnum.SHIPMENTTIME.getCode());
            }

            if (daysBetween > LIMIT_DAYS) {
                LOGGER.error(
                        "OTDServiceImpl.selectListByConditionsForCust shipmenttime difference is greater than 7 days");
                throw new IllegalArgumentException(ErrorCodeEnum.DAYS_INVALID.getCode());
            }
        } else if ((null == shipmentTimeFromDate && null != shipmentTimeToDate)
                || (null != shipmentTimeFromDate && null == shipmentTimeToDate)) {
            LOGGER.error(
                    "OTDServiceImpl.selectListByConditionsForCust param: shipmenttimeF and shipmenttimeT must be coexist or not exists");
            throw new IllegalArgumentException(ErrorCodeEnum.SHIPMENTTIME.getCode());
        }

        if (null != arriveTimeFromDate && null != arriveTimeToDate) {
            if (arriveTimeFromDate.after(arriveTimeToDate)) {
                LOGGER.error(
                        "OTDServiceImpl.selectListByConditionsForCust param: arrivetimeF must be less than arrivetimeT");
                throw new IllegalArgumentException(ErrorCodeEnum.ARRIVETIME_INVALID.getCode());
            }

            int arriveDaysBetween = 0;
            try {
                arriveDaysBetween = DateUtils.daysBetween(arriveTimeFromDate, arriveTimeToDate);
            } catch (ParseException e1) {
                LOGGER.error("OTDServiceImpl.selectListByConditionsForCust arrivetime between error");
                throw new IllegalArgumentException(ErrorCodeEnum.ARRIVETIME.getCode());
            }

            if (arriveDaysBetween > LIMIT_DAYS) {
                LOGGER.error(
                        "OTDServiceImpl.selectListByConditionsForCust arrivetime difference is greater than 7 days");
                throw new IllegalArgumentException(ErrorCodeEnum.DAYS_INVALID.getCode());
            }
        } else if ((null == arriveTimeFromDate && null != arriveTimeToDate)
                || (null != arriveTimeFromDate && null == arriveTimeToDate)) {
            LOGGER.error(
                    "OTDServiceImpl.selectListByConditionsForCust param: arrivetimeF and arrivetimeT must be coexist or not exists");
            throw new IllegalArgumentException(ErrorCodeEnum.ARRIVETIME.getCode());
        }
    }

    /**
     * 字符串转换成日期
     *
     * @param str
     * @return date
     */
    private static Date StrToDate(String str) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        format.setLenient(false);
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 字符串转换成日期
     *
     * @param str
     * @return date
     */
    private static Date StrWithClockToDate(String str) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        format.setLenient(false);
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}
